/**
 * 登录页面
 * 问题1：在键盘谈起德情况下切换tab，键盘类型不能及时更新
 */

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:frametrim/activity/webviewPage.dart';
import 'package:frametrim/app/app_navigator.dart';
import 'package:frametrim/http/ApiUtils.dart';
import 'package:frametrim/http/HttpManager.dart';
import 'package:frametrim/model/LoginM.dart';
import 'package:frametrim/route/Routes.dart';
import 'package:frametrim/utility/Tools.dart';
import 'package:frametrim/utility/dataServer.dart';
import 'package:frametrim/utility/screen.dart';
import 'package:frametrim/utility/sp_utils.dart';
import 'package:frametrim/utility/sq_color.dart';
import 'package:frametrim/utility/toast.dart';
import 'package:frametrim/views/checkbox_circle.dart';
import 'package:frametrim/views/input_background_view.dart';
import 'package:frametrim/views/lineargradient_view.dart';
import 'package:frametrim/views/multipleChoice/button_view.dart';
import 'package:frametrim/views/mydrivertabbarview.dart';
import 'package:frametrim/views/textfield_view.dart';
import 'package:get/get.dart';
import '../model/LoginGetUserInfoM.dart';
import '../route/controller/LoginColtroller.dart';
import 'package:dio/dio.dart';
import 'package:common_utils/common_utils.dart';
import 'mainPage.dart';

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => LoginPageState();
}

class LoginPageState extends State<LoginPage> {
  TextEditingController? _phoneController;

  TextEditingController _passwordController = TextEditingController();

  //是否选中标记
  bool _switchSelected = false;

  //隐私是否选中标记
  late bool isAgreement = false;
  var _currentIndex = 0;
  var hiteText = "请输入手机号";
  var mInputType = "PHONE";

  // final mController = Get.put(LoginColtroller());//这里记得加（）
  final mController = Get.put(LoginColtroller());

  @override
  void dispose() {
    super.dispose();
    _phoneController!.dispose();
    _passwordController.dispose();
  }

  @override
  void initState() {
    super.initState();
    /*监听eventBus,并进行操作*/
    // eventBus.on('PasswordEye', (arg) {
    //
    // });
    //获取从引导页传递过来的数据
    print("信息接收${mController.msg.toString()}");
    _phoneController = TextEditingController.fromValue(
        TextEditingValue(text: mController.msg.toString()));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        /*AnnotatedRegion 改变状态栏颜色*/
        body: /*SingleChildScrollView(
        child: (*/
            AnnotatedRegion(
                child: Stack(
                  /*alignment:指的是子Widget的对其方式
      * bottomEnd 所有组件以右下角为起点对齐，
      * topEnd     右上角为起点，
      * center     中心位置，
      * centerEnd  中心位置并且右边跟stack右边挨着，
      * bottomStart  左下角，
      * ...
      * */
                  alignment: AlignmentDirectional.topStart,
                  children: <Widget>[
                    //渐变背景
                    GradientView(
                        colors: [Color(0XFF3EA1FF), Color(0XFFFAFDFF)]),
                    Container(
                      width: Screen.width,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          SizedBox(height: 85 + Screen.topSafeHeight),
                          buildHeader(),
                          SizedBox(
                            height: 30,
                          ),
                          buildTab(),
                          SizedBox(
                            height: 30,
                          ),
                          buildEdittext(),
                          SizedBox(
                            height: 24,
                          ),
                          buildUserAgreement(),
                          SizedBox(
                            height: 10,
                          ),
                          ButtonView(
                            textStr: '登录',
                            textColor: Color(0xFFffffff),
                            borderRadius: 8,
                            borderColor: SQColor.color_0052D9,
                            fillColor: SQColor.color_0052D9,
                            onPress: login,
                          ),
                          // ButtonCircleView(
                          //     '登录', SQColor.white, SQColor.color_3C64F9, login),
                          SizedBox(
                            height: 16,
                          ),
                          _currentIndex == 0
                              ? /*ButtonCircleSingleView(
                                  '注册',
                                  SQColor.color_3C64F9,
                                  SQColor.color_3C64F9,
                                  register)*/
                              ButtonView(
                                  textStr: '注册',
                                  textColor: SQColor.color_0052D9,
                                  borderRadius: 8,
                                  borderColor: SQColor.color_0052D9,
                                  fillColor: SQColor.trans,
                                  onPress: login,
                                )
                              : Container(),
                          Expanded(child: Container()),
                          buildForgetPsw(),
                          SizedBox(
                            height: 40,
                          )
                        ],
                      ),
                    )
                  ],
                ),
                value: SystemUiOverlayStyle.dark)
        // ),
        // )
        );
  }

  /*头部logo*/
  Widget buildHeader() {
    return Column(
      children: <Widget>[
        /*圆角图片*/
        ClipRRect(
          borderRadius: BorderRadius.circular(5),
          child: Image.asset(
            'image/logo.png',
            width: 64,
            height: 64,
          ),
        ),
        SizedBox(
          height: 18,
        ),
        Text(
          '郑州市建设劳务服务平台',
          style: TextStyle(
              fontSize: 16,
              color: SQColor.color_90black,
              decoration: TextDecoration.none),
        ),
      ],
    );
  }

  /*Tabbar*/
  Widget buildTab() {
    return MyDriverTabBarView(
      mTitle1: '个人登录',
      mTitle2: '主管部门登录',
      unChooseColor: SQColor.color_90black,
      ChooseColor: SQColor.color_0052D9,
      lineColor: SQColor.color_7EB3E5,
      mFontSize: 18,
      onChooseListener: (index) {
        setState(() {
          _phoneController!.text = "";
          _currentIndex = index;
          if (_currentIndex == 0) {
            hiteText = '请输入手机号';
            mInputType = 'PHONE';
            SPUtil.putString(DataServer.mPlatform, "3");
          } else {
            hiteText = '请输入账号';
            mInputType = 'TEXT';
            SPUtil.putString(DataServer.mPlatform, "5");
          }
          print('_currentIndex==' + _currentIndex.toString());
        });
      },
    );
  }

  /*Tab+输入框*/
  Widget buildEdittext() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        //手机号
        InputBackGroundView(
            1,
            TextFieldView(
                inputStyle: "LEFT_PIC",
                inputType: mInputType,
                imageLeft: Image.asset(
                  'image/icon_acc_phone02.png',
                  width: 28,
                  height: 28,
                ),
                hiteText: hiteText,
                controller: _phoneController!)),

        SizedBox(
          height: 20,
        ),
        //密码
        InputBackGroundView(
            1,
            TextFieldView(
                inputStyle: "LEFT_PIC",
                inputType: "PSW",
                imageLeft: Image.asset(
                  'image/icon_acc_psd02.png',
                  width: 28,
                  height: 28,
                ),
                openEyes: Image.asset(
                  'image/psd_eye_on.png',
                  width: 24,
                  height: 24,
                ),
                closeEyes: Image.asset(
                  'image/psd_eye_off.png',
                  width: 24,
                  height: 24,
                ),
                hiteText: '请输入密码',
                controller: _passwordController)),
      ],
    );
  }

  /*用户协议*/
  Widget buildUserAgreement() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        RoundCheckBox(isAgreement),
        GestureDetector(
          onTap: () {
            setState(() {
              isAgreement = !isAgreement;
            });
          },
          child: (Text(
            '阅读并同意',
            style: TextStyle(fontSize: 16, color: SQColor.color_666666),
          )),
        ),
        GestureDetector(
          onTap: () {
            AppNavigator.push(
                context, WebViewPage("用户协议", ApiUtils.h5UserAgreen));
          },
          child: Text(
            '《用户协议》',
            style: TextStyle(fontSize: 16, color: SQColor.color_3C64F9),
          ),
        ),
        Text(
          '及',
          style: TextStyle(fontSize: 16, color: SQColor.color_666666),
        ),
        GestureDetector(
          onTap: () {
            AppNavigator.push(
                context, WebViewPage("隐私协议", ApiUtils.h5PrivateAgreen));
          },
          child: Text(
            '《隐私协议》',
            style: TextStyle(fontSize: 16, color: SQColor.color_3C64F9),
          ),
        ),
      ],
    );
  }

  /*忘记密码*/
  Widget buildForgetPsw() {
    return GestureDetector(
      onTap: () {
        if (_currentIndex == 0) {}
      },
      child: Text(
        _currentIndex == 0 ? '忘记密码' : '忘记密码，请直接联系平台管理员',
        style: TextStyle(
            color: _currentIndex == 0
                ? SQColor.color_0052D9
                : SQColor.color_60black,
            fontSize: 14),
      ),
    );
  }

  login() {
    print('点击登录');
    if (_currentIndex == 0) {
      DataServer.setmLoginType("0");
    } else {
      DataServer.setmLoginType("1");
    }
    if (_phoneController!.text.isEmpty) {
      ToastUtils.show("请输入账号");
      return;
    }
    if (_passwordController.text.isEmpty) {
      ToastUtils.show("请输入密码");
      return;
    }
    if (isAgreement == false) {
      ToastUtils.show("请阅读并同意《用户协议》及《隐私协议》");
      return;
    }
    getLogin();
  }

  void register() {
    print('点击注册');
    AppNavigator.pushToRegister(context);
  }

  /**
   * 登录platform
   */
  void getLogin() async {
    try {
      var map = Map<String, dynamic>();
      map["platform"] = SPUtil.getString(DataServer.mPlatform);
      map["username"] = _phoneController!.text;
      map["password"] = _passwordController.text;
      map["grant_type"] = "password";
      map["client_id"] = "rcb-authority";
      map["client_secret"] = "qidianb3Qvq2rcb";
      map["scope"] = "all";
      HttpManager.getInstance().post(context,ApiUtils.Login,
          params: map, contentType: Headers.formUrlEncodedContentType,
          successCallBack: (dataMap) {
        LoginM model = LoginM.fromJson(dataMap);
        SPUtil.putString(DataServer.mUserToken, model.records?.token);
        SPUtil.putString(DataServer.mPhone, model.records?.loginUserData?.phone);
        getUerInfoData();
      });
    } catch (e) {
      print(e);
    }
  }

  /**
   * 获取用户信息
   */
  void getUerInfoData() async {
    HttpManager.getInstance().addHeader().post(context,ApiUtils.getUserInfo,
        successCallBack: (dataMap) {
      LoginGetUserInfoM model = LoginGetUserInfoM.fromJson(dataMap);
      if (model.records?.laborCardId != null) {
        DataServer.setmLaborId(model.records?.laborCardId);
      }
      if (model.records?.id != null) {
        DataServer.setmUserId(model.records?.id.toString());
      }
      SPUtil.putString(DataServer.mPhone, model.records?.phone);
      //角色
      var roleList = model.records?.roleList;
      List<String?> roleIds = [];
      if (roleList != null && roleList.isNotEmpty) {
        roleList.forEach((element) {
          roleIds.add(element.id);
        });
      }
      var jsonStr = Tools.listToJson(roleIds);
      DataServer.setmRoleIds(jsonStr);
      //账号权限
      var menuList = model.records?.menuList;
      String json = Tools.listToJson(menuList);
      LogUtil.d("账号权限:$json");
      DataServer.setmAccountLimits(json);
      //身份证号
      if (model.records?.idCardNum != null) {
        DataServer.setidCardNum(model.records?.idCardNum);
      }
      Get.offNamed(Routes.MAIN);
      // AppNavigator.pushAndRemove(context, MainPage());
    });
  }
}
